/**
 * @author pshc
 */

$(function(){
	
	$('#quotation').datagrid({
		view: detailview,
		sortName:"id" ,
		sortOrder:"desc",
		pagination : true,
		fitColumns : true,
		border : false,
		fit : true,
		idField : 'id',
		rownumbers : "true",
		url : "quote/getquotation",
		singleSelect : "true",
		toolbar : "#quotationtoolbar",
		columns : [ 
			[ {
			field : "ck",
			checkbox : true
		}, {
			field : 'id',
			title : '编号',
			width : 50,
			hidden:true
		}, {
			field : 'quoId',
			title : '报价单编号',
			width : 100
		}, {
			field : 'theme',
			title : '主题',
			width : 100
		}, {
			field:"chance",
			title:'对应销售机会',
			width : 100,
			formatter : function(value, row, index) {
				var result = "("+value.id+")"+value.customer.name+"("+value.customer.linkWay+")"
				return result;
			}
		},{
			field : "createDate",
			title : "创建日期",
			width : 100,
			formatter : function(value, row, index) {
				return new Date(value).format("yyyy-MM-dd hh:mm:ss");
			}
		}, {
			field : 'total',
			title : '总金额(￥)',
			width : 100
		}] ],

		checkOnSelect : false,
		selectOnCheck : false, 
		
	    detailFormatter:function(index,row){   
	        
	        return "<div style='loat:left;height:400px;width:700px;border:1px solid #ddd;'><table  id='detail"+index+"'></table></div>";
	    },
		onClickRow:function(index,row){
				$('#quotation').datagrid("selectRow",index);
		},
		onExpandRow:function(index,row){
			var editIndex = undefined;
			
	        function endEditing(){
	            if (editIndex == undefined){return true}
	            
	            if ($("#detail"+index).datagrid('validateRow', editIndex)){
	            	
	                $("#detail"+index).datagrid('endEdit', editIndex);
	                editIndex = undefined;
	                return true;
	            } else {
	                return false;
	            }
	        }
			$("#detail"+index).datagrid({
				headerCls:'header',
				border : false,
				pagination : true,
				fit : true,
				idField : 'id',
				url : "quote/getquodetail?quotation="+row.id,
				singleSelect : "true",
				checkOnSelect : false,
				selectOnCheck : false,
				toolbar: [{
					iconCls: 'icon-add',
					text : "增加明细",
					handler: function(){
						 
						var wind = $("<div/>").dialog({
							title : '添加报价单商品('+row.quoId+")",
							width : 350,
							height : 320,
							modal : true,
							href:"quote/adddetail?quoteid="+row.id,
							openAnimation : "slide",
							buttons : [{
								iconCls : "icon-ok",
								text : "确认添加",
								handler : function() {
									var form = $("#adddetailform");
									// 校验表单数据
									if (form.form("validate")) { 
										var serial =  form.serialize();
										wind.dialog("destroy");
										$.post("quote/saveDetail",serial,function(result){
											
											if(result.errors){
												alert(result.errors);
											}else{
												$("#detail"+index).datagrid("reload");
												
												row.total=result.retur;
												
												$("#datagrid-row-r1-2-"+index).children("td[field=total]").children().html(result.retur);
												
											}
											
										})
									}
									
								}
							}, {
								iconCls : "icon-cancel",
								text : "关闭",
								handler : function() {
									wind.dialog("destroy");
								}
							} ],
							onClose : function() {
								wind.dialog("destroy");
							}
						}).dialog("open");
						
						
						
						
					}
				},{
					iconCls: 'icon-edit',
					text : "保存",
					handler: function(){
						if(endEditing()){
							alertWarn("保存成功");
						}
					
					}
				},{
					iconCls: 'icon-remove',
					text : "删除",
					handler: function(){
						var rows=$("#detail"+index).datagrid("getChecked");
						
						if(!rows.length){
							alertWarn("请选择要删除的行！！")
							return;
						}
						var rowid="";
						
						for(var i = 0;i<rows.length;i++){
							rowid+="detailId="+rows[i].id+"&";
						}
						
						var wind = $("<div/>").dialog({
							title : '提示！！',
							width : 220,
							height : 200,
							content : "<div style='margin:25px;font-size:15px;'>你确定要删除吗？</div>",
							modal : true,
							openAnimation : "slide",
							buttons : [{
								iconCls : "icon-ok",
								text : "确定",
								handler : function() {
									wind.dialog("destroy");
									$.post("quote/deletedetail",rowid,function(result){
										if(result.errors){
											alertWarn(result.errors);
										}else{
											$("#detail"+index).datagrid("reload");
											
											row.total=result.retur;
											$("#datagrid-row-r1-2-"+index).children("td[field=total]").children().html(result.retur);
											$("#detail"+index).datagrid("uncheckAll");
											$("#detail"+index).datagrid("unselectAll");
										}
									})
								}
							}, {
								iconCls : "icon-cancel",
								text : "关闭",
								handler : function() {
									wind.dialog("destroy");
								}
							} ],
							onClose : function() {
								wind.dialog("destroy");
							}
						}).dialog("open");
						
					
					}
				}],
				columns : [ [{
					field : "ck",
					checkbox : true
				},
				   {
					field : 'id',
					title : '编号',
					width : 50
				}, {
					field : 'product',
					title : '产品名称',
					width : 100,
					formatter : function(value, row, index) {
						return value.name;
					}
				}, {
					field : 'count',
					title : '产品数量',
					width : 100,
					editor:{
						type:"numberspinner",
						options:{
							min:1,
							editable:false
						}
					}
				}, {
					field:"cost",
					title:'折扣(%)',
					width : 100,
					editor:{
						type:"numberspinner",
						options:{
							min:1,
							max:100,
							editable:false
						}
					}
				}, {
					field:"wew",
					title:'单价',
					width : 100,
					formatter : function(value, row, index) {
						return row.product.sellPrice
					}
				} ,{
					field : 'total',
					title : '金额',
					width : 100,
					formatter : function(value, row, index) {
						return row.product.sellPrice*row.count*row.cost*0.01;
					}
				}] ],
				
				onClickCell:function(index1, field){
					if (editIndex != index1){
		                if (endEditing()){
		                    $("#detail"+index).datagrid('selectRow', index1)
		                            .datagrid('beginEdit', index1);
		                    editIndex = index1;
		                } else {
		                    setTimeout(function(){
		                        $("#detail"+index).datagrid('selectRow', editIndex);
		                    },0);
		                }
		            }
				},
				onEndEdit:function (index2, row){
					var param ={};
					param.cost=row.cost;
					param.count = row.count;
					param.detailId = row.id;
		           $.post("quote/editdetail",param,function(result){
		        	   if(result.errors){
		        		   alertWarn(result.errors);
		        	   }else{
		        		   row.total=result.retur;
							
		        		   $("#datagrid-row-r1-2-"+index).children("td[field=total]").children().html(result.retur);
		        	   }
		           })
		            
		        } 
			
			
			
			});
		}
		
	});
	
	
	$("#quotationtoolbar a.create").click(function(){
		
		var wind = $("<div/>").dialog({
		title : '创建报价单',
		width : 700,
		height : 200,
		href:"quote/createpage",
		modal : true,
		buttons : [ {
			iconCls : "icon-add",
			text:"确认创建报价单",
			handler : function() {
				var form = $("#quotationform");
				// 校验表单数据
				if (form.form("validate")) { 
					var serial =  form.serialize();
					wind.dialog("destroy");
					$.post("quote/createquote",serial,function(result){
						if(result.errors){
							alert(result.errors);
						}else{
							$('#quotation').datagrid("reload");
						}
					})
				}
			}
		},{
			iconCls : "icon-cancel",
			text : "关闭",
			handler : function() {
				wind.dialog("destroy");
			}
		} ],
		onClose : function() {
			wind.dialog("destroy");
		}
	}).dialog("open");
	})
	
	$("#quotationtoolbar .create_order").click(function(){
		var row = $('#quotation').datagrid("getSelected");

		if (!row) {
			alertWarn("请选择机会！")
			return;
		}
		$.post("quote/checkSuccess","quoteId="+row.id,function(result){
			if(result.success){
				$.messager.alert("提示",result.msg)
			}else{
				var wind = $("<div/>").dialog({
					title : '生成订单',
					width : 900,
					height :600,
					href : "quote/create_order?quoteId="+row.id,
					modal : true,
					buttons : [ {
						iconCls : "icon-add",
						text:"创建定单",
						handler : function() {
							var form = $("#quoteOrderForm");
							// 校验表单数据
							if (form.form("validate")) { 
								var serial =  form.serialize();
								wind.dialog("destroy");
								$.post("quote/createOrder",serial,function(result){
									if(result.success){
										$.messager.alert("提示","订单生成成功");
										$('#salemanager').datagrid("reload")
										$('#plan').datagrid("reload")
									}else{
										$.massager.alert("警告",result.msg);
									}
								})
							}
						}
					},{
						iconCls : "icon-cancel",
						text : "关闭",
						handler : function() {
							wind.dialog("destroy");
						}
					} ],
					onClose : function() {
						wind.dialog("destroy");
					}
				}).dialog("open");
			}
		})
		
	
		
		
		
		
		
	})
	
	
	
	$("#quotationtoolbar a.delete").click(function(){
		var rows=$('#quotation').datagrid("getChecked");
		
		if(!rows.length){
			alertWarn("请选择行！！")
			return;
		}
		var rowid="";
		
		for(var i = 0;i<rows.length;i++){
			rowid+="quotation="+rows[i].id+"&";
		}
		
		var wind = $("<div/>").dialog({
			title : '提示！！',
			width : 220,
			height : 200,
			content : "<div style='margin:25px;font-size:15px;'>删除该报表的同时会删除对应的详情表，你确定删除吗？</div>",
			modal : true,
			openAnimation : "slide",
			buttons : [{
				iconCls : "icon-ok",
				text : "确定",
				handler : function() {
					wind.dialog("destroy");
					$.post("quote/deletequotation",rowid,function(result){
						if(result.errors){
							alertWarn(result.errors);
						}else{
							$('#quotation').datagrid("reload");
							
							$('#quotation').datagrid("uncheckAll");
							$('#quotation').datagrid("unselectAll");
						}
					})
				}
			}, {
				iconCls : "icon-cancel",
				text : "关闭",
				handler : function() {
					wind.dialog("destroy");
				}
			} ],
			onClose : function() {
				wind.dialog("destroy");
			}
		}).dialog("open");
	})
	
	
	
	
	
	$('#quotationsearch').searchbox({
		searcher : function(value, name) {
			
			var param = {};
			
			param[name]=value;
			
			$('#quotation').datagrid("load",param);
			
		},
		width : 300,
		menu : '#quotationsearchitem',
		prompt : '请输入查找关键字'
	});
	
	
	$("#quotationtoolbar a.all").click(function() {
		
		$("#quotationsearch").searchbox("setValue","");
		
		$('#quotation').datagrid("load",{});
	})
	
	
	
	
	
})

function alertWarn(inform){
	var wind = $("<div/>").dialog({
		title : '警告！',
		width : 220,
		height : 160,
		content : "<div style='margin:25px;font-size:15px;'>"+inform+"</div>",
		modal : true,
		openAnimation : "slide",
		buttons : [ {
			iconCls : "icon-cancel",
			text : "关闭",
			handler : function() {
				wind.dialog("destroy");
			}
		} ],
		onClose : function() {
			wind.dialog("destroy");
		}
	}).dialog("open");
}